package com.example.casper.jnuexperiment2025;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class BookAdapter extends RecyclerView.Adapter<BookAdapter.BookViewHolder> {

    private List<Book> bookList;
    private int longClickedPosition;

    public int getLongClickedPosition() {
        return longClickedPosition;
    }

    public BookAdapter(List<Book> bookList) {
        this.bookList = bookList;
    }

    @NonNull
    @Override
    public BookViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_book, parent, false);
        return new BookViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull BookViewHolder holder, int position) {
        Book book = bookList.get(position);
        holder.bookName.setText(book.getTitle());
        holder.bookPrice.setText(String.format("¥ %.1f", book.getPrice()));
        holder.bookCover.setImageResource(book.getCoverResourceId());

        holder.itemView.setOnLongClickListener(v -> {
            longClickedPosition = holder.getAdapterPosition();
            return false; 
        });
    }

    @Override
    public int getItemCount() {
        return bookList.size();
    }

    static class BookViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
        ImageView bookCover;
        TextView bookName;
        TextView bookPrice;

        public BookViewHolder(@NonNull View itemView) {
            super(itemView);
            bookCover = itemView.findViewById(R.id.image_view_book_cover);
            bookName = itemView.findViewById(R.id.text_view_book_name);
            bookPrice = itemView.findViewById(R.id.text_view_book_price);
            itemView.setOnCreateContextMenuListener(this);
        }

        @Override
        public void onCreateContextMenu(android.view.ContextMenu menu, View v, android.view.ContextMenu.ContextMenuInfo menuInfo) {
            menu.add(0, 0, 0, "添加");
            menu.add(0, 1, 0, "更新");
            menu.add(0, 2, 0, "删除");
        }
    }
}